package com.idopartx.phonelightning.ui.home.calllightning

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.dotools.umlibrary.UMPostUtils
import com.idopartx.phonelightning.R
import com.idopartx.phonelightning.common.Constant
import com.idopartx.phonelightning.databinding.ActivityEditCommonLightningBinding
import com.idopartx.phonelightning.databinding.DialogExitBinding
import com.idopartx.phonelightning.entity.CallLightningCache
import com.idopartx.phonelightning.entity.CallLightningEntity
import com.idopartx.phonelightning.entity.LightNightVo
import com.idopartx.phonelightning.thread.LightningThread
import com.idopartx.phonelightning.ui.base.BaseActivity
import com.idopartx.phonelightning.utils.DialogUtil
import com.idopartx.phonelightning.viewmodel.CallLightingViewModel
import com.idopartx.phonelightning.widget.KBubbleSeekBar
import com.tencent.mmkv.MMKV
import com.wuhenzhizao.titlebar.widget.CommonTitleBar

/**
 * 编辑普通闪光
 */
class EditCommonLightningActivity : BaseActivity<ActivityEditCommonLightningBinding>() {

    companion object {
        const val INTENT_LIGHTNING_VO = Constant.INTENT_LIGHTNING_VO
    }

    private var position = -1

    private val viewModel: CallLightingViewModel by lazy {
        ViewModelProvider(this)[CallLightingViewModel::class.java]
    }

    private val callLightningCache: CallLightningCache? by lazy {
        val cache = MMKV.defaultMMKV()
            .decodeParcelable(Constant.MMKV_SAVE_CALL_LIGHTNING, CallLightningCache::class.java)

        cache
    }

    override fun initLayoutResId(): Int {
        return R.layout.activity_edit_common_lightning
    }

    private var thread: LightningThread? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.click = ClickProxy()

        position = intent.getIntExtra(EditMorseActivity.INTENT_POSITION, -1)

        val callLightningEntity =
            intent?.getParcelableExtra<CallLightningEntity>(INTENT_LIGHTNING_VO)

        viewModel.titleLiveData.value = if (callLightningEntity != null) {
            callLightningEntity.title
        } else {
            String.format(
                "普通%d",
                (callLightningCache?.callLightningList?.size ?: 0) + 1
            )
        }


        binding.viewTitleBar.setListener { v, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_LEFT_BUTTON -> {
                    onBackPressedSupport()
                }
            }
        }

        viewModel.lightNightLiveData.value =
            if (callLightningEntity?.lightNightList != null && callLightningEntity.lightNightList!!.isNotEmpty()) callLightningEntity.lightNightList else arrayListOf(
                LightNightVo(500, 500)
            )

        binding.viewModel = viewModel

        binding.etInputTitle.requestFocus()


        binding.sbLight.setProgress(
            (viewModel.lightNightLiveData.value?.get(0)?.light ?: 500).toFloat() / 10
        )
        binding.sbNight.setProgress(
            (viewModel.lightNightLiveData.value?.get(0)?.night ?: 500).toFloat() / 10
        )


        binding.sbLight.onProgressChangedListener =
            getOnProgressChangedListener("亮%dms", binding.tvLightNum)
        binding.tvLightNum.text = String.format("亮%dms", binding.sbLight.progress * 10)

        binding.sbNight.onProgressChangedListener =
            getOnProgressChangedListener("灭%dms", binding.tvNightNum)
        binding.tvNightNum.text = String.format("灭%dms", binding.sbNight.progress * 10)

    }

    private fun getOnProgressChangedListener(
        stringFormat: String,
        textView: TextView
    ): KBubbleSeekBar.OnProgressChangedListener {

        return object : KBubbleSeekBar.OnProgressChangedListener {
            override fun onProgressChanged(
                bubbleSeekBar: KBubbleSeekBar?,
                progress: Int,
                progressFloat: Float,
                fromUser: Boolean
            ) {
                textView.text = String.format(stringFormat, progress * 10)
            }

            override fun getProgressOnActionUp(
                bubbleSeekBar: KBubbleSeekBar?,
                progress: Int,
                progressFloat: Float
            ) {
            }

            override fun getProgressOnFinally(
                bubbleSeekBar: KBubbleSeekBar?,
                progress: Int,
                progressFloat: Float,
                fromUser: Boolean
            ) {

                viewModel.lightNightLiveData.value =
                    arrayListOf(
                        LightNightVo(
                            binding.sbLight.progress * 10,
                            binding.sbNight.progress * 10
                        )
                    )

                thread = null
                thread?.stopThread()
                thread = LightningThread(
                    applicationContext,
                    viewModel.lightNightLiveData.value,
                    4
                )
                thread?.start()
                textView.text = String.format(stringFormat, progress * 10)
            }

        }
    }

    override fun onBackPressedSupport() {

        if (checkEdit()) {
            finish()
            return
        }

        val dialogBinding = DataBindingUtil.inflate<DialogExitBinding>(
            LayoutInflater.from(this@EditCommonLightningActivity),
            R.layout.dialog_exit,
            null,
            false
        )
        val dialog = DialogUtil.getDialog(
            this@EditCommonLightningActivity,
            dialogBinding.root,
            DialogUtil.DialogGravity.CENTER
        )

        dialogBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }

        dialogBinding.tvConfirm.setOnClickListener {
            ClickProxy().saveAction()
        }

        dialog.show()
    }


    private fun checkEdit(): Boolean {
        if (position == -1) {
            return false
        }

        val callLightningEntity =
            intent?.getParcelableExtra<CallLightningEntity>(INTENT_LIGHTNING_VO)

        if (callLightningEntity?.lightNightList != viewModel.lightNightLiveData.value) {
            return false
        }
        return true
    }


    inner class ClickProxy {
        fun saveAction() {

            if (TextUtils.isEmpty(viewModel.titleLiveData.value)) {
                Toast.makeText(this@EditCommonLightningActivity, "请输入标题", Toast.LENGTH_SHORT).show()
                return
            }

            val eventMap = HashMap<String,String>()
            eventMap["call_normal_name"]  = viewModel.titleLiveData.value?:""
            UMPostUtils.onEventMap(this@EditCommonLightningActivity, "call_normal_save_click", eventMap)

            if (position != -1) {
                callLightningCache?.callLightningList?.get(position)?.apply {
                    title = binding.etInputTitle.text.toString()
                    isMorse = false
                    lightNightList = viewModel.lightNightLiveData.value
                }
            } else {
                val entity = CallLightningEntity(
                    binding.etInputTitle.text.toString(),
                    false,
                    viewModel.lightNightLiveData.value,
                )

                callLightningCache?.callLightningList?.add(0, entity)
            }
            MMKV.defaultMMKV().encode(Constant.MMKV_SAVE_CALL_LIGHTNING, callLightningCache)
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (thread != null) {
            thread?.stopThread()
            thread = null
        }
    }
}